package server;

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if (servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源servlet请求
                 /*HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, response);*/
                Class httpServlet = Bootstrap.httservlet.get(request.getUrl());
                if (null != httpServlet) {
                    Object requests = Bootstrap.classS
                            .get(request.getUrl() + Request.class.getSimpleName());

                    if (null != requests) {
                        Method setMethod = requests.getClass().getMethod("setMethod", String.class);
                        setMethod.invoke(requests, request.getMethod());
                        Method setUrl = requests.getClass().getMethod("setUrl", String.class);
                        setUrl.invoke(requests, request.getUrl());
                        Method setInputStream = requests.getClass()
                                .getMethod("setInputStream", InputStream.class);
                        setInputStream.invoke(requests, request.getInputStream());

                    }
                    Object responses = Bootstrap.classS
                            .get(request.getUrl() + Response.class.getSimpleName());
                    if (null != responses) {
                        Method setOutputStream = responses.getClass()
                                .getMethod("setOutputStream", OutputStream.class);
                        setOutputStream.invoke(responses, response.getOutputStream());
                    }

                    Object o = Bootstrap.classS.get(request.getUrl() + httpServlet.getSimpleName());
                    Method service = o.getClass()
                            .getMethod("doGet", requests.getClass(), responses.getClass());
                    service.invoke(o, requests, responses);

                }
            }

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
